<template>
  <div class="app-container question-new">
    <el-card>
      <div slot="header">{{ $route.query.id ? "试题修改" : "试题录入" }}</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 学科栏 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            @change="changeSubject"
            v-model="form.subjectID"
            class="inputwidth"
            size="medium"
          >
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录栏-->
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="form.catalogID" class="inputwidth">
            <el-option
              v-for="item in catalogOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业栏-->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="form.enterpriseID" class="inputwidth">
            <el-option
              v-for="item in enterpriseOptions"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市栏 -->
        <el-form-item label="城市：" prop="city">
          <el-select
            v-model="form.province"
            @change="getAreaOptions"
            style="width:17%"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select v-model="form.city" style="width:17%;margin-left:10px">
            <el-option
              v-for="item in areaOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向栏-->
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="form.direction" class="inputwidth">
            <el-option
              v-for="item in directionOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型栏-->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group @change="changeRadio({})" v-model="form.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value + ''"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 难度栏-->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value + ''"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 题干栏 -->
        <el-form-item label="题干：" prop="question">
          <quill-editor
            @blur="checkQustion"
            v-model="form.question"
            :options="editorOptions"
          ></quill-editor>
        </el-form-item>
        <!-- 选项栏-->
        <el-form-item
          label="选项："
          prop="options"
          v-if="form.questionType !== '3'"
        >
          <div
            class="option_item"
            v-for="item in form.options"
            :key="item.code"
          >
            <el-radio
              v-if="form.questionType === '1'"
              @change="changeRadio(item)"
              v-model="item.isRight"
              style="margin-right:0"
              :label="true"
              >{{ item.code }}：</el-radio
            >
            <el-checkbox
              v-if="form.questionType === '2'"
              v-model="item.isRight"
              style="margin-right:0"
              :label="true"
              >{{ item.code }}：</el-checkbox
            >
            <el-input v-model="item.title" style="width:240px"></el-input>
            <!-- action="https://jsonplaceholder.typicode.com/posts/" 上传图片问题
            改为 action="http://localhost:3000/upload"
            -->
            <el-upload
              style="margin-left:4px"
              class="avatar-uploader"
              action="http://localhost:3000/upload"
              :headers="{ Authorization: 'Bearer ' + token }"
              :on-success="
                (res, file) => {
                  uploadSuccess(item, res, file);
                }
              "
              :show-file-list="false"
            >
              <img v-if="item.img" :src="item.img" class="avatar" />
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </div>
          <!-- 添加按钮 -->
          <el-button
            type="danger"
            :disabled="form.questionType !== '2'"
            @click="addOption"
            size="small"
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <!-- 解析视频栏-->
        <el-form-item label="解析视频：">
          <el-input v-model="form.videoURL" class="inputwidth"></el-input>
        </el-form-item>
        <!-- 答案解析栏 -->
        <el-form-item label="答案解析：" prop="question">
          <quill-editor
            v-model="form.answer"
            :options="editorOptions"
          ></quill-editor>
        </el-form-item>
        <!-- 题目备注栏-->
        <el-form-item label="题目备注：">
          <el-input
            type="textarea"
            :rows="5"
            v-model="form.remarks"
            class="inputwidth"
          ></el-input>
        </el-form-item>
        <!-- 试题标签栏-->
        <el-form-item label="试题标签：" prop="tags">
          <el-select
            class="inputwidth"
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择试题标签"
          >
            <el-option
              v-for="item in tagsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 提交按钮-->
        <el-form-item>
          <el-button v-if="!$route.query.id" @click="submit()" type="primary"
            >确认提交</el-button
          >
          <el-button v-else @click="update()" type="success"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 学科简单列表
import { simple as getSubjectOptions } from "@/api/hmmm/subjects";
// 目录简单列表
import { simple as getCatalogOptions } from "@/api/hmmm/directorys";
// 标签简单列表
import { simple as getTagOptions } from "@/api/hmmm/tags";
// 企业管理列表
import { list as getCompanyOptions } from "@/api/hmmm/companys";
//  城市/地区
import {
  provinces as getCityOptions,
  citys as getAreaOptions
} from "@/api/hmmm/citys";

// 难度/题行/方向
import { direction, questionType, difficulty } from "@/api/hmmm/constants";
// 基础题库详情/添加/修改
import { add, detail, update } from "@/api/hmmm/questions";

// 富文本编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";

// 高亮显示
import hljs from "highlight.js";
import "highlight.js/styles/vs2015.css";

import { getToken } from "@/utils/auth";

export default {
  name: "QuestionsNew",
  components: {
    quillEditor
  },
  props: {},
  data() {
    return {
      token: getToken(),
      editorOptions: {
        placeholder: "",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            [{ list: "ordered" }, { list: "bullet" }],
            ["blockquote"],
            ["code-block", "image", "link"]
          ],
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      // 试题对象
      form: {
        subjectID: null,
        catalogID: null,
        enterpriseID: null,
        // 城市
        province: null,
        // 地区
        city: null,
        // 方向
        direction: null,
        // 题型
        questionType: "1",
        // 难度
        difficulty: "1",
        // 题干
        question: null,
        // 选项
        options: [
          { isRight: false, code: "A", title: "", img: "" },
          { isRight: false, code: "B", title: "", img: "" },
          { isRight: false, code: "C", title: "", img: "" },
          { isRight: false, code: "D", title: "", img: "" }
        ]
      },
      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: "请选择学科", trigger: "change" }
        ],
        catalogID: [
          { required: true, message: "请选择目录", trigger: "change" }
        ],
        enterpriseID: [
          { required: true, message: "请选择企业", trigger: "change" }
        ],
        city: [{ required: true, message: "请选择地区", trigger: "change" }],
        direction: [
          { required: true, message: "请选择方向", trigger: "change" }
        ],
        questionType: [
          { required: true, message: "请选择题型", trigger: "change" }
        ],
        difficulty: [
          { required: true, message: "请选择难度", trigger: "change" }
        ],
        tags: [{ required: true, message: "请选择标签", trigger: "blur" }],
        question: [{ required: true, message: "请输入题干", trigger: "blur" }]
      },
      // 学科选项
      subjectOptions: [],
      // 目录选项
      catalogOptions: [],
      // 企业选项
      enterpriseOptions: [],
      // 城市选项
      cityOptions: getCityOptions(),
      // 地区选项
      areaOptions: [],
      // 方向选项
      directionOptions: direction,
      // 题型选项
      questionType,
      // 难度选项
      difficulty,
      // 标签选项
      tagsOptions: []
    };
  },
  computed: {},
  watch: {
    "$route.query": function() {
      if (this.$route.query.id) {
        this.getQuestion();
      } else {
        this.form = {
          subjectID: null,
          catalogID: null,
          enterpriseID: null,
          province: null,
          city: null,
          direction: null,
          questionType: "1",
          difficulty: "1",
          question: null,
          options: [
            { isRight: false, code: "A", title: "", img: "" },
            { isRight: false, code: "B", title: "", img: "" },
            { isRight: false, code: "C", title: "", img: "" },
            { isRight: false, code: "D", title: "", img: "" }
          ]
        };
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      }
    }
  },
  created() {
    this.getSubjectOptions();
    this.getCompanyOptions();
    if (this.$route.query.id) {
      this.getQuestion();
    }
  },
  mounted() {},
  methods: {
    // 获取题目信息
    async getQuestion() {
      const { data } = await detail({ id: this.$route.query.id });
      data.tags = data.tags.split(",");
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1;
        return item;
      });
      this.form = data;
      const res = await getCatalogOptions({ subjectID: this.form.subjectID });
      this.catalogOptions = res.data;
      const res2 = await getTagOptions({ subjectID: this.form.subjectID });
      this.tagsOptions = res2.data;
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0);
      });
    },
    // 改变学科
    async changeSubject(subjectID) {
      this.form.catalogID = null;
      const res = await getCatalogOptions({ subjectID: this.form.subjectID });
      this.catalogOptions = res.data;
      this.form.tags = null;
      const res2 = await getTagOptions({ subjectID: this.form.subjectID });
      this.tagsOptions = res2.data;
    },
    // 提交
    submit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.form };
          data.tags = data.tags.join(",");
          await add(data);
          this.$message.success("添加成功");
          this.$router.push("/questions/list"); // 页面添加成功后跳转基础题库
        }
      });
    },
    update() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.form };
          data.tags = data.tags.join(",");
          await update(data);
          this.$message.success("修改成功");
          this.$router.push("/questions/list"); // 页面修改成功后跳转基础题库
        }
      });
    },
    // 上传成功
    uploadSuccess(item, res, file) {
      item.img = URL.createObjectURL(file.raw);
    },
    // 添加选项
    addOption() {
      this.form.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.form.options.length),
        title: "",
        img: ""
      });
    },
    // 点击单选框选项 添加和禁用
    changeRadio(item) {
      this.form.options.forEach(item => {
        item.isRight = false;
      });
      item.isRight = true;
    },
    // 校验题干
    checkQustion() {
      this.$refs.form.validateField("question");
    },
    async getSubjectOptions() {
      const res = await getSubjectOptions();
      this.subjectOptions = res.data;
    },
    async getCompanyOptions() {
      const res = await getCompanyOptions({ pagesize: 10000 });
      this.enterpriseOptions = res.data.items;
    },
    getAreaOptions(cityName) {
      this.form.city = null;
      this.areaOptions = getAreaOptions(cityName);
    }
  }
};
</script>

<style scoped lang="scss">
.inputwidth {
  width: 35%;
}
.question-new ::v-deep .ql-editor {
  height: 200px;
}
.question-new ::v-deep .ql-toolbar.ql-snow {
  padding: 0 8px;
}
.option_item {
  padding-bottom: 20px;
}
.question-new ::v-deep .avatar-uploader {
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}
.question-new ::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.question-new ::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader i {
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
}
</style>
